package com.example.managemyself.ui.tasks;

import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.managemyself.R;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.viewmodel.TaskViewModel;
import com.example.managemyself.util.TaskCompletionNotifier;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TaskAdapter extends RecyclerView.Adapter<TaskAdapter.TaskViewHolder> {

    private List<Task> tasks = new ArrayList<>();
    private final TaskViewModel taskViewModel;
    private OnTaskInteractionListener listener;
    private TaskCompletionNotifier taskCompletionNotifier;

    public TaskAdapter(TaskViewModel viewModel) {
        this.taskViewModel = viewModel;
        this.taskCompletionNotifier = TaskCompletionNotifier.getInstance();
    }
    
    public void setOnTaskInteractionListener(OnTaskInteractionListener listener) {
        this.listener = listener;
    }
    
    /**
     * 任务交互监听器接口
     */
    public interface OnTaskInteractionListener {
        void onTaskClick(Task task);
        void onTaskLongClick(Task task);
        void onTaskStatusChanged(Task task, boolean isCompleted);
    }

    @NonNull
    @Override
    public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_task, parent, false);
        return new TaskViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
        Task currentTask = tasks.get(position);
        holder.bind(currentTask);
    }

    @Override
    public int getItemCount() {
        return tasks.size();
    }

    public void setTasks(List<Task> tasks) {
        this.tasks = new ArrayList<>(tasks);
        sortTasks();
    }

    private void sortTasks() {
        Collections.sort(tasks, (t1, t2) -> {
            // 规则1: 已完成的永远排在最后
            if (t1.isCompleted() != t2.isCompleted()) {
                return t1.isCompleted() ? 1 : -1;
            }

            // 对于所有未完成的任务，应用四象限排序法则
            // 规则2: 按重要性降序 (值越大越重要)
            if (t1.getImportance() != t2.getImportance()) {
                return Integer.compare(t2.getImportance(), t1.getImportance());
            }

            // 规则3: 在重要性相同的情况下，按紧急程度升序 (值越小越紧急)
            if (t1.getUrgencyValue() != t2.getUrgencyValue()) {
                return Integer.compare(t1.getUrgencyValue(), t2.getUrgencyValue());
            }

            // 规则4: 在上述都相同的情况下，按创建时间降序 (最新的在前)
            return t2.getCreatedDate().compareTo(t1.getCreatedDate());
        });
        notifyDataSetChanged();
    }

    class TaskViewHolder extends RecyclerView.ViewHolder {
        private final TextView tvTitle;
        private final TextView tvDescription;
        private final CheckBox cbCompleted;

        public TaskViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tv_task_title);
            tvDescription = itemView.findViewById(R.id.tv_task_description);
            cbCompleted = itemView.findViewById(R.id.cb_task_completed);
        }

        public void bind(final Task task) {
            tvTitle.setText(task.getTitle());
            tvDescription.setText(task.getDescription());
            
            cbCompleted.setOnCheckedChangeListener(null);
            cbCompleted.setChecked(task.isCompleted());

            updateStrikeThrough(tvTitle, task.isCompleted());

            cbCompleted.setOnCheckedChangeListener((buttonView, isChecked) -> {
                boolean wasCompleted = task.isCompleted();
                task.setCompleted(isChecked);
                taskViewModel.updateTask(task);
                
                // 如果任务从未完成变为完成，通知日记系统
                if (!wasCompleted && isChecked) {
                    taskCompletionNotifier.notifyTaskCompleted(task);
                }
                
                // 通知监听器
                if (listener != null) {
                    listener.onTaskStatusChanged(task, isChecked);
                }
                
                sortTasks(); // 重新排序列表
            });
        }

        private void updateStrikeThrough(TextView textView, boolean isCompleted) {
            if (isCompleted) {
                textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
                textView.setPaintFlags(textView.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
            }
        }
    }
}